<template>
	<view class="delay-list pb-60">
		<view>
			<view class="search">
				<view style="background-color: #fff;margin: 0 10px;border-radius: 5px;height: 42px;" class="uni-flex">
					<view style="-webkit-flex: 1;flex: 1;" class="uni-flex">
						<view class="date-p"><uni-datetime-picker type="daterange" v-model="createdAtRange"
								:border="false" placeholder="起始-终止日期" @change="changeDate" />
						</view>
					</view>
				</view>
			</view>
			<view class="uni-mlr-10">
				<z-paging ref="paging" v-model="dataList" @query="queryList">
					<!-- 设置自己的emptyView组件，非必须。空数据时会自动展示空数据组件，不需要自己处理 -->
					<view slot="empty" class="empty text-center text-sm"><text>暂时没有数据~</text>
					</view>
					<view>
						<view class=" uni-mb-5 delay-item uni-mlr-10"
							:style="{paddingBottom:item.planeNo||item.originC||item.destC?'6px':'12px'}"
							v-for="(item,index) in dataList" :key="index">
							<view class="uni-flex">
								<view class="checkbox-icon">
									<checkbox-group @change.stop="changeCheckItem(item,$event)">
										<checkbox style="transform:scale(0.7);" :checked="item.checked"
											:value="item.eventId" color="#0c6eb7" />
									</checkbox-group>
								</view>
								<view @click="goUploadCredial(item)" style="flex:1">
									<view class="uni-flex uni-row">
										<view class="text uni-flex left-logo">
											<image :src="item.airImage" mode="widthFix"></image>
										</view>
										<view class="uni-flex uni-column right-info">
											<view class="uni-flex" >
												<view class="text title">
													{{item.flightNo}}
												</view>
												<view class="text uni-flex right-status">
													<text class="status" style="background-color:#0c6eb7"
														v-if="item.aOrD=='A'">进港</text>
													<text class="status" style="background-color:#FF9800"
														v-if="item.aOrD=='D'">出港</text>
												</view>
											</view>
											<view class="uni-flex uni-row"  style="justify-content: space-between;">
												<view class="date">航班日期：{{item.flightDate}}</view>
												<view @click.stop="toggleMore(item)" style="padding:10px;position: absolute;right: 0;top:3px;"><uni-icons :type="item.showMore?'up':'down'" color="#999" size="20"></uni-icons></view>
											</view>
										</view>
									</view>
									<view class="uni-flex uni-row dest" style="margin-top: 5px;"
										v-if="item.planeNo||item.originC||item.destC">
										<view class="item" v-if="item.planeNo">
											<view class="val">{{item.planeNo}}</view>
											<text class="label">机号</text>
										</view>
										<view class="item" v-if="item.originC">
											<view class="val">{{item.originC}}</view>
											<text class="label">出发地</text>
										</view>
										<view class="item" v-if="item.destC">
											<view class="val">{{item.destC}}</view>
											<text class="label">目的地</text>
										</view>
									</view>
								</view>
							</view>
							<view class="fee-detail" v-if="item.showMore">
								<view class="uni-flex fee-detail-item" v-if="item.signatureLst && item.signatureLst.length>0">
									<view class='type'>签名</view>
									<view class="detail">
										<text v-if="getSignatureText(item, 1)">制单人签字：{{getSignatureText(item, 1)}}</text>
										<text v-if="getSignatureText(item, 2)">地面保障部签字：{{getSignatureText(item, 2)}}</text>
										<text v-if="getSignatureText(item, 3)">航司签字：{{getSignatureText(item, 3)}}</text>
									</view>
								</view>
								<view class="uni-flex fee-detail-item" v-if="item.lstFee && item.lstFee.materialall">
									<view class='type'>材料-全员</view>
									<view class="detail">
										<text v-if="item.lstFee.materialall.drink">饮料费：{{item.lstFee.materialall.drink}}</text>
										<text v-if="item.lstFee.materialall.breakfast">早餐费：{{item.lstFee.materialall.breakfast}}</text>
										<text v-if="item.lstFee.materialall.lunch">午餐费：{{item.lstFee.materialall.lunch}}</text>
										<text v-if="item.lstFee.materialall.dinner">晚餐费：{{item.lstFee.materialall.dinner}}</text>
										<text v-if="item.lstFee.materialall.night">夜宵/点心：{{item.lstFee.materialall.night}}</text>
										<text v-if="item.lstFee.materialall.hotel">住宿费：{{item.lstFee.materialall.hotel}}</text>
										<text v-if="item.lstFee.materialall.car">地面交通费：{{item.lstFee.materialall.car}}</text>
										<text v-if="item.lstFee.materialall.pay">补偿费：{{item.lstFee.materialall.pay}}</text>
										<text v-if="item.lstFee.materialall.memo">备注：{{item.lstFee.materialall.memo}}</text>
										<text v-if="item.lstFee.materialall.totalPrice">总计金额：￥{{item.lstFee.materialall.totalPrice}}</text>
										
									</view>
								</view>
								<view class="uni-flex fee-detail-item" v-if="item.lstFee && item.lstFee.materialpsg">
									<view class='type'>材料-旅客</view>
									<view class="detail">
										<text v-if="item.lstFee.materialpsg.drink">饮料费：{{item.lstFee.materialpsg.drink}}</text>
										<text v-if="item.lstFee.materialpsg.breakfast">早餐费：{{item.lstFee.materialpsg.breakfast}}</text>
										<text v-if="item.lstFee.materialpsg.lunch">午餐费：{{item.lstFee.materialpsg.lunch}}</text>
										<text v-if="item.lstFee.materialpsg.dinner">晚餐费：{{item.lstFee.materialpsg.dinner}}</text>
										<text v-if="item.lstFee.materialpsg.night">夜宵/点心：{{item.lstFee.materialpsg.night}}</text>
										<text v-if="item.lstFee.materialpsg.hotel">住宿费：{{item.lstFee.materialpsg.hotel}}</text>
										<text v-if="item.lstFee.materialpsg.car">地面交通费：{{item.lstFee.materialpsg.car}}</text>
										<text v-if="item.lstFee.materialpsg.pay">补偿费：{{item.lstFee.materialpsg.pay}}</text>
										<text v-if="item.lstFee.materialpsg.memo">备注：{{item.lstFee.materialpsg.memo}}</text>
										<text v-if="item.lstFee.materialpsg.totalPrice">总计金额：￥{{item.lstFee.materialpsg.totalPrice}}</text>
									</view>
								</view>
								<view class="uni-flex fee-detail-item" v-if="item.lstFee && item.lstFee.materialgrp">
									<view class='type'>材料-机组</view>
									<view class="detail">
										<text v-if="item.lstFee.materialgrp.drink">饮料费：{{item.lstFee.materialgrp.drink}}</text>
										<text v-if="item.lstFee.materialgrp.breakfast">早餐费：{{item.lstFee.materialgrp.breakfast}}</text>
										<text v-if="item.lstFee.materialgrp.lunch">午餐费：{{item.lstFee.materialgrp.lunch}}</text>
										<text v-if="item.lstFee.materialgrp.dinner">晚餐费：{{item.lstFee.materialgrp.dinner}}</text>
										<text v-if="item.lstFee.materialgrp.night">夜宵/点心：{{item.lstFee.materialgrp.night}}</text>
										<text v-if="item.lstFee.materialgrp.hotel">住宿费：{{item.lstFee.materialgrp.hotel}}</text>
										<text v-if="item.lstFee.materialgrp.car">地面交通费：{{item.lstFee.materialgrp.car}}</text>
										<text v-if="item.lstFee.materialgrp.pay">补偿费：{{item.lstFee.materialgrp.pay}}</text>
										<text v-if="item.lstFee.materialgrp.memo">备注：{{item.lstFee.materialgrp.memo}}</text>
										<text v-if="item.lstFee.materialgrp.totalPrice">总计金额：￥{{item.lstFee.materialgrp.totalPrice}}</text>
									</view>
								</view>
								<view class="uni-flex fee-detail-item" v-if="item.lstFee && item.lstFee.pay">
									<view class='type'>现金</view>
									<view class="detail">
										<text v-if="item.lstFee.pay.drink">饮料费：{{item.lstFee.pay.drink}}</text>
										<text v-if="item.lstFee.pay.breakfast">早餐费：{{item.lstFee.pay.breakfast}}</text>
										<text v-if="item.lstFee.pay.lunch">午餐费：{{item.lstFee.pay.lunch}}</text>
										<text v-if="item.lstFee.pay.dinner">晚餐费：{{item.lstFee.pay.dinner}}</text>
										<text v-if="item.lstFee.pay.night">夜宵/点心：{{item.lstFee.pay.night}}</text>
										<text v-if="item.lstFee.pay.hotel">住宿费：{{item.lstFee.pay.hotel}}</text>
										<text v-if="item.lstFee.pay.car">地面交通费：{{item.lstFee.pay.car}}</text>
										<text v-if="item.lstFee.pay.pay">补偿费：{{item.lstFee.pay.pay}}</text>
										<text v-if="item.lstFee.pay.memo">备注：{{item.lstFee.pay.memo}}</text>
										<text v-if="item.lstFee.pay.totalPrice">总计金额：￥{{item.lstFee.pay.totalPrice}}</text>
									</view>
								</view>
								<view class="uni-flex fee-detail-item" v-if="item.lstFee && item.lstFee.oversell">
									<view class='type'>超售</view>
									<view class="detail">
										<text v-if="item.lstFee.oversell.drink">饮料费：{{item.lstFee.oversell.drink}}</text>
										<text v-if="item.lstFee.oversell.breakfast">早餐费：{{item.lstFee.oversell.breakfast}}</text>
										<text v-if="item.lstFee.oversell.lunch">午餐费：{{item.lstFee.oversell.lunch}}</text>
										<text v-if="item.lstFee.oversell.dinner">晚餐费：{{item.lstFee.oversell.dinner}}</text>
										<text v-if="item.lstFee.oversell.night">夜宵/点心：{{item.lstFee.oversell.night}}</text>
										<text v-if="item.lstFee.oversell.hotel">住宿费：{{item.lstFee.oversell.hotel}}</text>
										<text v-if="item.lstFee.oversell.car">地面交通费：{{item.lstFee.oversell.car}}</text>
										<text v-if="item.lstFee.oversell.pay">补偿费：{{item.lstFee.oversell.pay}}</text>
										<text v-if="item.lstFee.oversell.memo">备注：{{item.lstFee.oversell.memo}}</text>
										<text v-if="item.lstFee.oversell.totalPrice">总计金额：￥{{item.lstFee.oversell.totalPrice}}</text>
									</view>
								</view>
							</view>

						</view>

					</view>
				</z-paging>
			</view>

		</view>
		<!-- 底部按钮 -->
		<!-- <view class="bottom-btn-fixed">
			<view>
				<button class="btn-f" type="primary" @click="scanQrCode">扫一扫</button>
				<button class="btn-f btn-f-all" type="primary" @click="viewAll">查看全部</button>
			</view>
		</view> -->
		<!-- 底部按钮 -->
		<view class="bottom-btn-fixed">
			<view>
				<!-- <button class="btn-f" type="primary" @click="handleShowCheckBox" v-if="!showCheckBox">显示勾选框</button> -->
				<!-- <button class="btn-f" type="primary" @click="checkAllOrNo" v-if="showCheckBox">全选/全不选</button> -->
				<view style="font-size: 26rpx;line-height: 30px;">
					<checkbox-group @click="changeCheckAllOrNo">
						<checkbox style="transform:scale(0.7);margin-top: 3px;" :checked="checkedAll" value="all"
							color="#0c6eb7" />全选/全不选
					</checkbox-group>
				</view>
				<!-- <button class="btn-f" type="primary" @click="handleHideCheckBox" v-if="showCheckBox">隐藏勾选框</button> -->
				<button class="btn-f" type="primary" @click="batchSign">批量签字</button>

				<button class="btn-f" type="primary" @click="scanQrCode">扫一扫</button>
				<button class="btn-f btn-f-all" type="primary" @click="viewAll">查看全部</button>
			</view>
		</view>
		<!-- 弹出批量签名 -->
		<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff">
			<view>
				<uni-section :title="'请签字'+(companyCode&&companyCode.length?'（航司）':'')+'（航班数量：'+selectedNum+'）'"
					type="line">
					<view class="uni-flex uni-m-5" style="padding: 12px 10px;padding-top: 0;"
						v-if="!(companyCode&&companyCode.length)">
						<text style="line-height: 24px;">签字人：</text>
						<uni-data-checkbox v-model="signRoleVal" :localdata="signRoleRange"
							@change="changeSignRole"></uni-data-checkbox>
					</view>
					<view class="example-body"
						style="border:dashed 1px #0c6eb7;margin: 0 10px;border-radius: 5px;height: 300px;position: relative;">
						<l-signature disableScroll :key="1" ref="signatureRef" penColor="black" :penSize="5"
							:openSmooth="false" v-if="delaySign"></l-signature>
					</view>
					<view class="uni-flex uni-mt-5" style="justify-content: center;">
						<button class="uni-btn uni-btn-small" @click="onClick('clear')" size="mini">清空</button>
						<button class="uni-btn uni-btn-small" @click="onClick('save')" type="primary"
							size="mini">保存</button>
					</view>
				</uni-section>
			</view>

		</uni-popup>
	</view>
</template>

<script>
	import configService from '@/common/service/config.service.js';

	export default {
		data() {
			return {
				createdAt: '',
				createdAtRange: [],
				startDate: '',
				endDate: '',
				url: {
					list: '/fd/queryv3',
					getFlightImage: '/flightImage/',
				},
				dataList: [],
				flightId: '',
				token: '',
				// airImage:''
				checkedAll: false,
				selectedNum: 0,
				delaySign: false,
				signRoleVal: 1,
				signRoleRange: [{
					"value": 1,
					"text": "制单人"
				}, {
					"value": 2,
					"text": "地面保障部"
				}],
				companyCode: null, //登录时存储的判断是否是航司用户登录的，有值就表示是航司用户,
				saveSignUrl: "/fd/airSettleSigns",
			}
		},
		onLoad(e) {
			this.token = uni.getStorageSync('token') || 'b4a841e50aa54ed1bb00433c2ceee83d'
			this.createdAt = this.getPrevMonthDate(Date.now())
			this.endDate = this.getDate(Date.now())
			this.startDate = this.getPrevMonthDate(this.endDate)
			this.createdAtRange = [this.startDate, this.endDate]
			// console.log(this.token);
			this.companyCode = uni.getStorageSync('companyCode');
			console.log(e);
			if (e.flightId) {
				this.flightId = e.flightId;
			}

		},
		onShow() {
			this.queryList(1, 10)
		},
		methods: {
			// ...mapActions(['loginByLoginCode']),
			queryList(pageNo, pageSize) {
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				//这里的请求只是演示，请替换成自己的项目的网络请求，请在网络请求回调中
				//通过this.$refs.paging.complete(请求回来的数组);将请求结果传给z-paging
				let me = this
				var params = {
					page: pageNo,
					limit: pageSize,
					startDate: this.startDate,
					endDate: this.endDate,
					token: this.token,
					// flightDate: this.createdAt
				}
				if (this.flightId.length) {
					params.flightId = this.flightId
				}
				this.$http.post('/fd/queryv3', params).then(res => {
					console.log(res.data)
					if (res.data.errcode == 0) {
						// me.newsList=res.data.result.records
						// let tempData = res.data.data;
						// for (let i = 0; i < tempData.length; i++) {
						// 	if (tempData[i].airImage && tempData[i].airImage.length) {
						// 		let split = tempData[i].airImage.split('/')
						// 		let flatN = split[split.length - 1]
						// 		uni.request({
						// 			url: configService.apiUrl.replace(/\/m\//, '') + this.url
						// 				.getFlightImage + flatN,
						// 			responseType: "arraybuffer",
						// 			success: async function(res) {
						// 				// console.log(res);
						// 				let datas = res.data
						// 				//将arrayBuffer数据转换成base64格式即可显示 
						// 				// me.airImage = `data:image/jpeg;base64,${uni.arrayBufferToBase64(datas)}` 
						// 				tempData[i].airImageUrl =
						// 					`data:image/jpeg;base64,${uni.arrayBufferToBase64(datas)}`
						// 			},
						// 		})
						// 	}
						// }
						// this.$refs.paging.complete(res.data.data);
						setTimeout(() => {
							this.$refs.paging.complete(res.data.data);
						}, 300)

					} else {
						uni.showToast({
							title: res.data.errmsg,
							icon: "none"
						})
					}
				})
			},
			// 获取航司Logo图片
			getAirImage(url) {
				if (url && url.length) {
					let split = url.split('/')
					let flatN = split[split.length - 1]
					let me = this
					uni.request({
						url: configService.apiUrl.replace(/\/m\//, '') + this.url.getFlightImage + flatN,
						responseType: "arraybuffer",
						success: async function(res) {
							let datas = res.data
							//将arrayBuffer数据转换成base64格式即可显示 
							me.airImage = `data:image/jpeg;base64,${uni.arrayBufferToBase64(datas)}`
							// console.log(me.airImage);
							return me.airImage
						},
					})
				}


			},
			changeDate(e) {
				console.log('----change事件:', e);
				this.checkedAll = false
				this.flightId = ''
				// this.createdAt = e
				this.startDate = e[0]
				this.endDate = e[1]
				this.queryList(1, 10)
			},
			goUploadCredial(item) {
				let copyData = JSON.parse(JSON.stringify(item))
				if (copyData.airImageUrl) delete copyData.airImageUrl
				if (copyData.lstFee) delete copyData.lstFee
				if (copyData.signatureLst) delete copyData.signatureLst
				// copyData.airImageUrl字符串太长了，传递不过去
				uni.navigateTo({
					url: '/pages/index/uploadCredentialAndSign?data=' + JSON.stringify(copyData)
				})
			},
			scanQrCode() {
				let me = this;
				uni.scanCode({
					onlyFromCamera: true,
					scanType: 'qrCode',
					hideAlbum: true,
					success: async function(res) {
						// console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						// loginCode:7yu328ewru238hedj238u2390rudi19u32rf923j|flightId:6tgh9876tghj976tghji976tghjio
						if (res.result.includes('|')) {
							// let loginCode = res.result.split('|')[0].split(':')[1]
							let flightId = res.result.split('|')[1].split(':')[1]
							// console.log(loginCode, flightId);
							// let obj = Object.assign({},  {loginCode: loginCode})
							me.flightId = flightId
							uni.reLaunch({
								url: '/pages/index/delayList?flightId=' + flightId
							})

						} else {
							// res.result.split('|')
							let loginCode = res.result.split(':')[1]
							// let obj = Object.assign({},  {loginCode: loginCode})
							uni.reLaunch({
								url: './delayList'
							})
						}

					}
				})
			},
			viewAll() {
				this.flightId = ''
				uni.reLaunch({
					url: './delayList'
				})
			},
			getDate(date) {
				date = new Date(date)
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()
				return `${year}-${this.addZero(month)}-${this.addZero(day)}`
			},
			getPrevMonthDate(date) {
				// 解析输入日期
				const currentDate = new Date(date);
				const year = currentDate.getFullYear();
				const month = currentDate.getMonth(); // 0-11（0代表1月）

				// 计算上个月的年份和月份
				let prevYear = year;
				let prevMonth = month - 1;

				// 处理跨年（1月的前一个月是12月）
				if (prevMonth < 0) {
					prevMonth = 11; // 12月
					prevYear = year - 1;
				}

				// 获取上个月的最后一天（解决日期溢出问题）
				const lastDayOfPrevMonth = new Date(prevYear, prevMonth + 1, 0).getDate();

				// 获取当前日期的天数，并确保不超过上个月的最大天数
				const currentDay = currentDate.getDate();
				const adjustedDay = Math.min(currentDay, lastDayOfPrevMonth);

				// 格式化为 YYYY-MM-DD
				return `${prevYear}-${this.addZero(prevMonth + 1)}-${this.addZero(adjustedDay)}`;
			},
			addZero(num) {
				if (num < 10) {
					num = `0${num}`
				}
				return num
			},
			changeCheckAllOrNo() {
				this.checkedAll = !this.checkedAll
				if (this.checkedAll) {
					// this.checkedAll = true
					this.dataList.forEach((item) => item.checked = true)
				} else {
					// this.checkedAll = false
					this.dataList.forEach((item) => item.checked = false)
				}

			},
			changeCheckItem(item, e) {
				// console.log(item,e);
				if (e.detail.value.length) {
					// item.checked = true
					this.$set(item, 'checked', true)
				} else {
					// item.checked = false
					this.checkedAll = false
					this.$set(item, 'checked', false)
				}

			},
			batchSign() {
				// console.log(this.dataList);
				this.selectedNum = this.dataList.filter((item) => item.checked == true).length
				if (this.selectedNum == 0) {
					uni.showToast({
						title: "未选中任何航班",
						icon: "none"
					})
					return
				}

				setTimeout(() => {
					this.delaySign = true
					this.$refs.popup.open('bottom')
					this.$refs.signatureRef.clear()
				}, 200);
			},
			async onClick(type) {
				let that = this;
				if (type == 'save') {
					let flightIds = this.dataList.filter((item) => item.checked == true).map(item => item.flightId)
						.join('|')
					this.$refs.signatureRef.canvasToTempFilePath({
						success: (res) => {
							// 是否为空画板 无签名
							// console.log(res.isEmpty)
							// console.log(res)
							// 微信小程序-生成图片的临时路径
							// 执行图片转base64方法
							that.base64(res.tempFilePath, "png").then(res => {
								console.log(res, 'base64路径') //res是base64路径
								that.url = res
								// console.log(res);
								let params = {
									type: (this.companyCode && this.companyCode.length) ? 3 :
										this.signRoleVal, //1：制单人签字 2:地面保障部签字 3：航司签字
									token: that.token,
									flightIds: flightIds,
									signature: that.url
								}
								that.$http.post(that.saveSignUrl, params).then(res => {
									// console.log(res)
									if (res.data.errcode == 0) {
										uni.showToast({
											title: '保存成功',
											icon: "success"
										})
										that.delaySign = false
										that.$refs.popup.close()
										setTimeout(() => {
											that.queryList(1, 10)
											that.checkedAll = false
										}, 200);


									} else {
										uni.showToast({
											title: res.data.errmsg,
											icon: "none"
										})
									}
								})
							})

						}
					})

				} else {
					this.$refs.signatureRef.clear()

				}
			},
			changeSignRole(e) {
				console.log('e:', e);
				if (e.detail.value != this.signRoleVal) {
					this.$refs.signatureRef.clear()
				}
				this.signRoleVal = e.detail.value
			},
			// 图片转64
			base64(url, type) {
				return new Promise((resolve, reject) => {
					wx.getFileSystemManager().readFile({
						filePath: url, //选择图片返回的相对路径
						encoding: 'base64', //编码格式
						success: res => {
							// resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
							resolve(res.data)
						},
						fail: res => reject(res.errMsg)
					})
				})
			},
			toggleMore(item){
				console.log(item);
				item.showMore = !item.showMore
				this.$forceUpdate()
			},
			getSignatureText(item, type) {
				if (item.signatureLst && item.signatureLst.length) {
					const signature = item.signatureLst.find(sig => sig.type === type);
					if (signature) {
						return signature.userId || '已签字';
					}
				}
				return '';
			}
		}
	}
</script>

<style>
	.delay-list .z-paging-content {
		top: 60px !important;
	}

	/* #ifdef H5 */
	.delay-list .z-paging-content {
		top: 90px !important;
	}

	/* #endif */
</style>